package com.fernfx.xingtan.common.photo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.fernfx.xingtan.Constant;
import com.fernfx.xingtan.common.base.BaseActivity;
import com.fernfx.xingtan.my.ui.MySettingActivity;
import com.fernfx.xingtan.user.AccountManager;
import com.fernfx.xingtan.utils.GlideUtil;
import com.fernfx.xingtan.utils.LogUtils;
import com.fernfx.xingtan.utils.OtherUtil;
import com.fernfx.xingtan.utils.PhotoUtils;
import com.fernfx.xingtan.utils.ToastUtil;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Map;

import static com.fernfx.xingtan.utils.OtherUtil.hasSdcard;

/**
 * Created by admin on 2018/8/13.
 * 打开相机或者相册的activity只要继承该activity即可调用
 */
public class PhotoActivity extends BaseActivity {

    //打开相机的回调
    public static final int CODE_GALLERY_REQUEST = 0xa0;
    public static final int CODE_CAMERA_REQUEST = 0xa1;
    public static final int CODE_RESULT_REQUEST = 0xa2;
    public static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    public static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;

    //相片保存的路径
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    //打开系统组件的uri
    private Uri imageUri;
    //裁剪后照片路径
    protected File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri cropImageUri;
    //裁剪后的图片的大小
    private static int output_X = 480;
    private static int output_Y = 480;
    //图片允许最大空间   单位：KB
    double maxSize = 400.00;
    //显示图片imageview
    protected ImageView imageLogoIv;
    //token
    protected String token;
    //上传文件名
    //指定上传的路径
    protected String accountText;
    //handler
    private Handler uploadHandler = initHandler();
    private HandlerThread handlerThread = null;
    //图片上传成功后的动作
    protected UploadSucessCallback uploadSucessCallback;

    @Override
    protected int getLayoutResId() {
        return 0;
    }

    public void autoObtainCameraPermission() {
        final BaseActivity currentActivity = this;
        if (ContextCompat.checkSelfPermission(currentActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(currentActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(currentActivity, Manifest.permission.CAMERA)) {
                ToastUtil.showCentertoast("您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(currentActivity, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MySettingActivity.CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (OtherUtil.hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    imageUri = FileProvider.getUriForFile(currentActivity, "com.fernfx.xingtan", fileUri);//通过FileProvider创建一个content类型的Uri
                PhotoUtils.takePicture(currentActivity, imageUri, MySettingActivity.CODE_CAMERA_REQUEST);
            } else {
                ToastUtil.showCentertoast("设备没有SD卡！");
            }
        }
    }

    /**
     * 自动获取sdk权限
     */
    public void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CAMERA_PERMISSIONS_REQUEST_CODE: {//调用系统相机申请拍照权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imageUri = FileProvider.getUriForFile(mContext, "com.fernfx.xingtan", fileUri);//通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        ToastUtil.showCentertoast("设备没有SD卡！");
                    }
                } else {

                    ToastUtil.showBottomtoast("请允许打开相机！！");
                }
                break;
            }
            case STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {
                    ToastUtil.showBottomtoast("请允许打操作SDCard！！");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            newUri = FileProvider.getUriForFile(this, "com.fernfx.xingtan.fileprovider", new File(newUri.getPath()));
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        ToastUtil.showCentertoast("设备没有SD卡！");
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        imageZoom(bitmap);
                        //显示imageview
                        if (imageLogoIv != null) {
                            imageLogoIv.setBackground(null);
                            imageLogoIv.setImageBitmap(bitmap);
                            System.gc();
                        }

                        //check upload file
                        if (!(null != fileCropUri && fileCropUri.exists())) {
                            ToastUtil.showCentertoast("文件不能为空");
                            return;
                        }
                        //设置文件名称
                        String mobileText = AccountManager.getUserInfo().getObj().getMobile();
                        String fileName = mobileText +"_"+System.currentTimeMillis()+".jpg";
                        //发送请求
                        Message message = uploadHandler.obtainMessage();
                        message.obj = fileName;
                        uploadHandler.sendMessage(message);
                    }
                    break;
            }
        }
    }

    private void imageZoom(Bitmap bitMap) {
        //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        //将字节换成KB
        double mid = b.length / 1024;
        //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            //获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
            //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
                    bitMap.getHeight() / Math.sqrt(i));
        }
    }


    /***
     * 图片的缩放方法
     *
     * @param bgimage
     *            ：源图片资源
     * @param newWidth
     *            ：缩放后宽度
     * @param newHeight
     *            ：缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        //释放旧的bitmap
        if (!bgimage.isRecycled()) {
            bgimage.recycle();
            bgimage = null;
            System.gc();
        }
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != fileUri) {
            fileUri = null;
        }
        if (null != imageUri) {
            imageUri = null;
        }
        if (null != fileCropUri) {
            fileCropUri = null;
        }
        if (null != cropImageUri) {
            cropImageUri = null;
        }
        if (null != imageLogoIv) {
            imageLogoIv = null;
        }
        if (null != handlerThread) {
            handlerThread.quit();
            handlerThread = null;
        }
        if (uploadHandler != null) {
            uploadHandler = null;
        }
        if (null != uploadSucessCallback) {
            uploadSucessCallback = null;
        }
    }

    /*
     * init handler
     */
    private Handler initHandler(){
        handlerThread = new HandlerThread("upload thread");
        handlerThread.setPriority(Thread.NORM_PRIORITY);
        handlerThread.start();
        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .build();
        //init UploadManager
        final UploadManager uploadManager = new UploadManager(config);
        return new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                //upload
                String fileName = null != msg.obj ? msg.obj.toString() : "";
                uploadManager.put(fileCropUri, fileName, token,
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, org.json.JSONObject response) {
                                //res包含hash、key等信息，具体字段取决于上传策略的设置
                                if (info.isOK()) {
                                    LogUtils.i("Upload Success");
                                    if (null != uploadSucessCallback && !TextUtils.isEmpty(key)) {
                                        uploadSucessCallback.request(key);
                                    }
                                } else {
                                    ToastUtil.showCentertoast("上传失败,请重新上传");
                                    LogUtils.e("Upload Fail");
                                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                }
                                LogUtils.i(key + ",\r\n " + info + ",\r\n " + info.path);
                            }
                        }, new UploadOptions(null, null, false, new UpProgressHandler() {
                            @Override
                            public void progress(String key, double percent) {

                            }
                        }, new UpCancellationSignal() {
                            public boolean isCancelled() {
                                return false;
                            }
                        }));
            }
        };
    }

    public interface UploadSucessCallback{
        void request(String imgPath);
    }
}
